package com.app.couponsharelife.ui.main.home

import android.animation.ObjectAnimator
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.alibaba.baichuan.trade.biz.login.AlibcLogin
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.AppBarLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.message.MessageActivity
import com.app.couponsharelife.ui.main.home.search.HQTGoodsListActivity
import com.app.couponsharelife.ui.main.home.search.SearchSelecteActivity
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.main.home.shopweb.TaoBaoWebActivity
import com.app.couponsharelife.ui.main.home.shopweb.WebActivity
import com.app.couponsharelife.ui.main.me.invite.ShareInvitePicActivity
import com.app.couponsharelife.ui.main.special.NewManFreeActivity
import com.app.couponsharelife.ui.popupwindow.HomeClassPopupWindow
import com.app.couponsharelife.ui.view.MarqueeView
import com.app.couponsharelife.ui.view.ScaleGeneralTitleView
import com.app.couponsharelife.ui.viewfactory.HomeFactory
import com.app.couponsharelife.utils.AppUtils
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.youth.banner.Banner
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_choiceness.*
import kotlinx.android.synthetic.main.fragment_home.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import java.util.HashMap
import java.util.concurrent.TimeUnit

/**
 * Created by xct on 2019/4/9
 */
class HomeFragment : LazyFragment(), OnClickListener {
    private var newHomeFactory: HomeFactory? = null
    private var commonNavigator: CommonNavigator? = null
    private var classList = arrayListOf<HomeClassBean>()
    private var popupwindow: HomeClassPopupWindow? = null
    private var mClipboardManager: ClipboardManager? = null
    private var disposable: Disposable? = null
    private var mLastPosition = 0
    private var mCopyContent = ""
    private var mOnPrimaryClipChangedListener: ClipboardManager.OnPrimaryClipChangedListener? = null
    private var animType = false
    private var homeActivityLink: HomeActivityLink? = null
    private var distance = 0f

    private val boboDataList= arrayListOf<HomeBroadcastBean>()
    private var broadcastList= arrayListOf<String>()

    var ivTopBg: ImageView? = null
    var ll_BBJ: LinearLayout? = null
    var appbarLayout: AppBarLayout? = null
    var newhomefragViewpager: ViewPager? = null
    var choicenessShopRV: RecyclerView? = null
    var choicenessMBanner: Banner? = null
    var choicenessLlXSJC: LinearLayout? = null

    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    override val viewLayoutId: Int get() = R.layout.fragment_home

    companion object {
        fun newInstance(): HomeFragment {
            val fragment = HomeFragment()
            fragment.arguments = Bundle()
            return fragment
        }

        private fun getBroadcast(homeFragment: HomeFragment){
            val map = HashMap<String, String>()
            //mViewModel?.freshBroadcast(map,isRefresh)
            map["userId"] = AppUtils.getString(Contacts.USERID, "")
            RetrofitWorker.retrofitWorker.getBoBOData(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object :DisposableObserver<RemoteResultBean<List<HomeBroadcastBean>>>(){
                        override fun onComplete() {

                        }

                        override fun onNext(it: RemoteResultBean<List<HomeBroadcastBean>>) {
                            if (it.data!=null&&it.data!!.isNotEmpty()){
                                homeFragment.boboDataList.clear()
                                homeFragment.boboDataList.addAll(it.data!!)
                                homeFragment.broadcastList.clear()
                                val list=it.data!!
                                for (i in 0 until list.size){
                                    var nikeName=list[i].sellerName?:""
                                    var title=list[i].itemName?:""
                                    var price=list[i].commission?:"0.0"
                                    price = "获得预估佣金<font color=\"#FF0038\">￥$price</font>"
                                    nikeName=if (nikeName.isNotEmpty()&&nikeName.length>1){
                                        nikeName.substring(0,1)+"**  "
                                    }else if(nikeName.isNotEmpty()){
                                        "$nikeName**  "
                                    }else{
                                        nikeName
                                    }
                                    title=if (title.isNotEmpty()&&title.length>16){
                                        "购买了"+title.substring(0,16)+"...  "
                                    }else{
                                        "购买了$title  "
                                    }
                                    homeFragment.broadcastList.add("$nikeName$title$price >>")
                                }
                                homeFragment.choiceness_marqueeView!!.setOnItemClickListener(object : MarqueeView.OnItemClickListener{
                                    override fun onItemClick(position: Int, textView: TextView) {
                                        val data= homeFragment.boboDataList[position]
                                        val goodBean= TaobaoGoodBean()
                                        goodBean.item_id=data.itemId?:""
                                        goodBean.volume="0"
                                        goodBean.goodsSource1="好单库"
                                        goodBean.small_images=""
                                        goodBean.pict_url=""
                                        val intent = Intent(homeFragment.context, GoodDetailActivity::class.java)
                                        intent.putExtra("good", goodBean)
                                        homeFragment.startActivity(intent)
                                    }
                                })
                                homeFragment.choiceness_marqueeView!!.startWithList(homeFragment.broadcastList)
                            }
                        }

                        override fun onError(e: Throwable) {

                        }
                    })
        }



    }

    override fun initViews() {
        newHomeFactory = HomeFactory()

        ivTopBg = newhomefrag_topbg
        ll_BBJ = llBBJ
        appbarLayout = home_appbarlayout
        newhomefragViewpager = newhomefrag_viewpager
        choicenessShopRV = choiceness_shopRV
        choicenessMBanner = choiceness_mBanner
        choicenessLlXSJC = choiceness_llXSJC

        newhomefrag_lltitle.post {
            val layoutparams = newhomefrag_lltitle.layoutParams as ConstraintLayout.LayoutParams
            layoutparams.width = AppUtils.getDisplayMetrics(context!!).widthPixels
            layoutparams.height = AppUtils.getStatusBarHeight(activity!!)
            newhomefrag_lltitle.layoutParams = layoutparams
        }
        home_ivXL.setOnClickListener {
            showPopupWindow()
        }
        newhomefrag_rlmessage.setOnClickListener {
            startActivity(Intent(activity, MessageActivity::class.java))
        }
        newhomefrag_llsearch.setOnClickListener {
            val intent = Intent(activity, SearchSelecteActivity::class.java)
            intent.putExtra("Type", 0)
            startActivity(intent)
        }
        home_tvGWC.setOnClickListener {
            showToastMsg("正在开发中，敬请期待！")
            //startActivity(Intent(activity, BrandSpecialActivity::class.java))
            //WXMiniProgramUtil.start(context!!)
        }
        home_tvYQM.setOnClickListener {
            startActivity(Intent(activity, ShareInvitePicActivity::class.java))
        }
        /*ivSearchClose.setOnClickListener {
            home_clSearchContent?.visibility=View.GONE
        }
        tvSearchPDD.setOnClickListener {
            home_clSearchContent?.visibility=View.GONE
            val intent=Intent(context, HomeSearchActivity::class.java)
            intent.putExtra("KeyWord",mCopyContent)
            intent.putExtra("SearchType","PDD")
            startActivity(intent)
        }
        tvSearchTB.setOnClickListener {
            home_clSearchContent?.visibility=View.GONE
            val intent=Intent(context, HomeSearchActivity::class.java)
            intent.putExtra("KeyWord",mCopyContent)
            intent.putExtra("SearchType","TB")
            startActivity(intent)
        }
        home_clSearchContent.setOnClickListener {

        }*/
        newhomefrag_activityBut.setOnClickListener {
            if (homeActivityLink != null) {
                val type = homeActivityLink!!.type ?: ""
                when (type) {
                    "Link" -> {
                        val intent = Intent(activity, ShopWebActivity::class.java)
                        intent.putExtra("url", homeActivityLink!!.link ?: "")
                        startActivity(intent)
                    }
                    "H5" -> {  //网页
                        val intent = Intent(activity, ShopWebActivity::class.java)
                        intent.putExtra("url", homeActivityLink!!.link ?: "")
                        intent.putExtra("name", homeActivityLink!!.name ?: "")
                        startActivity(intent)
                    }
                    "PRODUCT" -> {  //选品库
                        val intent = Intent(activity, HQTGoodsListActivity::class.java)
                        intent.putExtra("FavoritesID", homeActivityLink!!.link ?: "")
                        intent.putExtra("ImagUrl", homeActivityLink!!.image_url ?: "")
                        intent.putExtra("Name", homeActivityLink!!.name ?: "")
                        startActivity(intent)
                    }
                    "SDK_Link" -> {
                        val relationId = AppUtils.getString(Contacts.ADZONE_ID, "")
                        if (relationId.isNotEmpty()) {
                            goTaoBao(homeActivityLink!!.link ?: "" + "&relationId=${relationId}")
                        } else {
                            //getAliLonginUrl()
                            taobaoLogin()
                        }
                    }
                    "SDK_H5" -> {
                        val relationId = AppUtils.getString(Contacts.ADZONE_ID, "")
                        if (relationId.isNotEmpty()) {
                            //val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                            val intent = Intent(context, TaoBaoWebActivity::class.java)
                            intent.putExtra("url", homeActivityLink!!.link ?: ""
                            + "&relationId=${relationId}")
                            intent.putExtra("name", homeActivityLink!!.name ?: "")
                            startActivity(intent)
                            //goTaoBao(url + "&relationId=${relationId}")
                        } else {
                            //getAliLonginUrl()
                            taobaoLogin()
                        }
                    }
                    "NEWMENFREE" -> {
                        val intent = Intent(context, NewManFreeActivity::class.java)
                        intent.putExtra("FavoritesID", homeActivityLink!!.link ?: "")
                        intent.putExtra("Name", homeActivityLink!!.name ?: "新人0元购")
                        startActivity(intent)
                    }
                }
            }
        }
        popupwindow = HomeClassPopupWindow(context!!, classList, this)
        popupwindow!!.setOnDismissListener {
            newhomefrag_tablayout.visibility = View.VISIBLE
            home_ivXL.visibility = View.VISIBLE
        }
        distance = (AppUtils.getDisplayMetrics(context!!).widthPixels * 0.133 * 0.8).toFloat()
        getData()
    }

    private fun showPopupWindow() {
        if (popupwindow == null) {
            popupwindow = HomeClassPopupWindow(context!!, classList, this)
            popupwindow!!.setOnDismissListener {
                newhomefrag_tablayout.visibility = View.VISIBLE
                home_ivXL.visibility = View.VISIBLE
            }
        }
        if (!popupwindow!!.isShowing) {
            popupwindow!!.showAsDropDown(choiceness_shopRV, 0, 0)
            newhomefrag_tablayout.visibility = View.INVISIBLE
            home_ivXL.visibility = View.INVISIBLE
        }
    }

    override fun click(arg1: Int, arg2: Any) {
        newhomefrag_viewpager.setCurrentItem(arg1, true)
    }

    override fun lazyLoad() {

    }

    override fun onResume() {
        super.onResume()
        registerClipEvents()
        Companion.getBroadcast(this)
    }

    override fun onPause() {
        super.onPause()
        hideSearchWindow()
    }

    fun hideSearchWindow() {
        //home_clSearchContent?.visibility=View.GONE
    }

    private fun setViewPager() {
        //setTopBG()
        home_ivXL.visibility = View.VISIBLE
        newhomefrag_viewpager.offscreenPageLimit = 6
        newhomefrag_viewpager.adapter = object : FragmentPagerAdapter(childFragmentManager) {
            override fun getItem(position: Int): Fragment {
                return newHomeFactory!!.createFragment(position, classList[position])
            }

            override fun getCount(): Int {
                return classList.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return classList[position].name
            }
        }
        newhomefrag_viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                if (position == 0) {
                    //setTopBG()
                    ivTopBg?.visibility = View.VISIBLE
                    newhomefrag_bgtop.visibility = View.INVISIBLE
                } else {
                    popupwindow!!.setIndex(position - 1)
                    newhomefrag_bgtop.visibility = View.VISIBLE
                    val homeClassBean = classList[position]
//                    ivTopBg?.visibility = View.INVISIBLE

                    //设置fragment头部图片
//                    Glide.with(this@HomeFragment).asBitmap()
//                            .apply(RequestOptions().error(R.drawable.home_default_bg).placeholder(R.drawable.home_default_bg))
//                            .load(Contacts.NEWREMOTE_IMAGE_URL + homeClassBean.bgImg)
//                            .into(newhomefrag_bgtop)
                }
            }
        })
        commonNavigator = CommonNavigator(activity)
        commonNavigator!!.adapter = object : CommonNavigatorAdapter() {
            override fun getTitleView(p0: Context, p1: Int): IPagerTitleView {
                val colorTransitionPagerTitleView = ScaleGeneralTitleView(p0)
                colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.gray_f3f4)
                colorTransitionPagerTitleView.textSize = 16f
                colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.white)
                colorTransitionPagerTitleView.text = classList[p1].name
                colorTransitionPagerTitleView.setOnClickListener { newhomefrag_viewpager.currentItem = p1 }
                return colorTransitionPagerTitleView
            }

            override fun getCount(): Int {
                return classList.size
            }

            override fun getIndicator(p0: Context?): IPagerIndicator? {
                val indicator = LinePagerIndicator(p0)
                indicator.setColors(resources.getColor(R.color.white))
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.lineWidth = AppUtils.dip2px(context!!, 20f).toFloat()
                indicator.lineHeight = AppUtils.dip2px(context!!, 2f).toFloat()
                return indicator
            }
        }
        newhomefrag_tablayout.navigator = commonNavigator
        ViewPagerHelper.bind(newhomefrag_tablayout, newhomefrag_viewpager)
    }

    private fun setTopBG() {
        newhomefrag_topbg.visibility = View.VISIBLE
        newhomefrag_bgtop.visibility = View.INVISIBLE
        val homeClassBean = classList[0]
        Glide.with(this@HomeFragment)
                .asBitmap()
                .apply(RequestOptions().error(R.drawable.ic_tribe_boy_thumb))
                .load(Contacts.NEWREMOTE_IMAGE_URL + homeClassBean.bgImg)
                .into(newhomefrag_topbg)
    }

    private fun getData() {
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        RetrofitWorker.retrofitWorker.getNewHomeClass(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<List<HomeClassBean>>>() {
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<HomeClassBean>>) {
                        dismissProgressDialog()
                        if (it.code == 200) {
                            if (it.data!!.isNotEmpty()) {
                                classList.clear()
                                /*val myHomeClassBean=HomeClassBean()
                                myHomeClassBean.name="精选"
                                classList.add(myHomeClassBean)*/
                                classList.addAll(it.data!!)
                                setViewPager()
                                getLink()
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException) {
                            showToastMsg(e.msg)
                        } else {
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }

    private fun getLink() {
        val map = HashMap<String, String>()
        RetrofitWorker.retrofitWorker.getAlipayLink(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<HomeActivityLink>>() {
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HomeActivityLink>) {
                        if (200 == it.code) {
                            if (it.data != null) {
                                newhomefrag_activityBut.visibility = View.VISIBLE
                                homeActivityLink = it.data!!
                                val url = Contacts.REMOTE_IMAGE_URL + it.data!!.image_url ?: ""
                                if (url.isNotEmpty() && url.contains(".gif")) {
                                    Glide.with(activity!!)
                                            .asGif()
                                            .apply(RequestOptions().error(R.drawable.ic_tribe_boy_thumb))
                                            .load(url)
                                            .into(newhomefrag_activityBut)
                                } else {
                                    Glide.with(activity!!)
                                            .asBitmap()
                                            .apply(RequestOptions().error(R.drawable.ic_tribe_boy_thumb))
                                            .load(url)
                                            .into(newhomefrag_activityBut)
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        newhomefrag_activityBut.visibility = View.GONE
                    }
                })
    }

    private fun getAliLonginUrl() {
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        RetrofitWorker.retrofitWorker.getAuthUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>() {
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200 == it.code) {
                            val url = it.data ?: ""
                            if (url.isNotEmpty()) {
                                val intent = Intent(context, WebActivity::class.java)
                                intent.putExtra("url", url)
                                intent.putExtra("name", "淘宝授权")
                                startActivity(intent)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException) {
                            if ("502" == e.code.toString()) {

                            } else {
                                showToastMsg(e.msg)
                            }
                        } else {
                            showToastMsg("数据加载出错！")
                        }
                    }
                })
    }

    fun visibilityAnim() {
        if (!animType) {
            return
        }
        val mAnimatorA = ObjectAnimator.ofFloat(newhomefrag_activityBut, View.TRANSLATION_X, distance, 0f).setDuration(500)
        mAnimatorA.start()
        newhomefrag_activityBut.clearAnimation()
        animType = false
    }

    fun goneAnim() {
        if (animType) {
            return
        }
        val mAnimatorA = ObjectAnimator.ofFloat(newhomefrag_activityBut, View.TRANSLATION_X, 0f, distance).setDuration(500)
        mAnimatorA.start()
        animType = true
    }

    private fun taobaoLogin() {
        showProgressDialog("请稍后")
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.showLogin(object : AlibcLoginCallback {
            override fun onSuccess(p0: Int) {
                //showToastMsg("登录成功 ")
                //获取淘宝用户信息
                //Log.i("eee", "获取淘宝用户信息: "+AlibcLogin.getInstance().session)
                dismissProgressDialog()
                //getAliLoginUrl()
                getAliLonginUrl()
            }

            override fun onFailure(p0: Int, p1: String?) {
                //showToastMsg("登录失败")
                dismissProgressDialog()
            }
        })
    }

    private fun goTaoBao(url: String) {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改
        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID //+ AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = "65231850041"//AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = HashMap()
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["relationId"] = AppUtils.getString(Contacts.ADZONE_ID, "")
        if (url == "") {
            showToastMsg("该商品暂时不能购买")
            return
        }
        val rlid = "&relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"
        AlibcTrade.show(activity, AlibcPage(url + rlid), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }

    private fun registerClipEvents() {
        //Log.e("eee","开启复制监听")
        if (disposable == null) {
            disposable = Observable
                    .just("main")
                    .delay(3, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe() {
                        mClipboardManager = context!!.getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
                        mOnPrimaryClipChangedListener = ClipboardManager.OnPrimaryClipChangedListener {
                            if (mClipboardManager!!.hasPrimaryClip() && mClipboardManager!!.primaryClip != null && mClipboardManager!!.primaryClip.itemCount > 0) {
                                // 获取复制、剪切的文本内容
                                /*val copyContent = mClipboardManager!!.primaryClip.getItemAt(0).text.toString()
                                val content=AppUtils.getString(Contacts.COPY_SEARCH_CONTENT,"")
                                Log.e("eee","监听到复制：${copyContent}")
                                if (copyContent.isNotEmpty()&& content != copyContent) {
                                    AppUtils.setString(Contacts.COPY_SEARCH_CONTENT, copyContent)
                                    home_clSearchContent.visibility=View.VISIBLE
                                    tvSearchContent.text=copyContent
                                }*/
                            } else {

                            }
                        }
                        if (mClipboardManager!!.primaryClip != null) {
                            val copyContent = mClipboardManager!!.primaryClip.getItemAt(0).text.toString()
                            val content = AppUtils.getString(Contacts.COPY_SEARCH_CONTENT, "")
                            //Log.e("eee","监听到复制：${copyContent}------>${content}")
                            if (copyContent.isNotEmpty() && content != copyContent) {
                                AppUtils.setString(Contacts.COPY_SEARCH_CONTENT, copyContent)
                                //home_clSearchContent?.visibility=View.VISIBLE
                                mCopyContent = copyContent
                                //tvSearchContent.text=copyContent
                            }
                            mClipboardManager!!.addPrimaryClipChangedListener(mOnPrimaryClipChangedListener)
                            disposable?.dispose()
                            disposable = null
                        }
                    }
        }
    }
}